package edu.chalmers;

import android.content.Intent;
import android.os.Bundle;
import android.widget.EditText;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;

public class EditActivity extends SherlockActivity{
	private SharedBookManager bookManager = SharedBookManager.getBookManager();
	private EditText editAuthor, editTitle, editIsbn, editCourse, editPrice;
	private Book currentBook;
	
   public void onCreate(Bundle icicle){
      super.onCreate(icicle);
      setContentView(R.layout.edit);
      
      ActionBar actionBar = getSupportActionBar();
      actionBar.setDisplayHomeAsUpEnabled(true);
      actionBar.setDisplayShowTitleEnabled(false);
      
      Intent intent = getIntent();
      int position = intent.getIntExtra(Book.TITLE, 0);
      currentBook = bookManager.bookAtIndex(position);
      
      editAuthor = (EditText) findViewById(R.id.editAuthor);
      editAuthor.setText(currentBook.getAuthor());
      editTitle = (EditText) findViewById(R.id.editTitle);
      editTitle.setText(currentBook.getTitle());
      editIsbn = (EditText) findViewById(R.id.editIsbn);
      editIsbn.setText(currentBook.getIsbn());
      editCourse = (EditText) findViewById(R.id.editCourse);
      editCourse.setText(currentBook.getCourse());
      editPrice = (EditText) findViewById(R.id.editPrice);
      editPrice.setText(""+currentBook.getPrice());
   }
   
   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
       MenuInflater inflater = getSupportMenuInflater();
       inflater.inflate(R.layout.add_menu, menu);
       return true;
   }
   
   @Override
   public boolean onOptionsItemSelected(MenuItem item) {
	   int id = item.getItemId();
//	   switch (item.getItemId()) {
//	   	case android.R.id.home:
	   if(id == android.R.id.home){
	   		setResult(RESULT_OK);
	   		finish();
	   		return true;
	   } else if(id == R.id.menu_saveBook){
//	   	case R.id.menu_saveBook:
	   		String newAuthor = editAuthor.getText().toString();
	   		String newTitle = editTitle.getText().toString();
	   		String newIsbn = editIsbn.getText().toString();
	   		String newCoruse = editCourse.getText().toString();
	   		int newPrice = 0;
	   		if(!editPrice.getText().toString().equals("")){
	   			newPrice = Integer.parseInt(editPrice.getText().toString());
	   		}
	   		bookManager.editBook(
	   				currentBook,
	   				bookManager.createBook(newAuthor, newTitle, newIsbn, newCoruse, newPrice));
	   		setResult(RESULT_OK);
	   		finish();
	   		return true;
	   } else{
//	   	default:
   			return super.onOptionsItemSelected(item);
   		}
	}
}
